<template>
  <div>
    <div class="image-upload">
      <el-upload
        action="#"
        list-type="picture-card"
        :http-request="uploadFn"
        :file-list="fileList"
        :on-remove="removeFn"
        :[attr]="limit"
        :class="{disable:limit&&fileList.length>0}"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-progress v-if="percentShow" :text-inside="true" :stroke-width="18" :percentage="percent" status="success" />
    </div>
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDgRF0kOq44pMfjbI2Yt8Qiv9HGD6qTyQ6',
  SecretKey: 'e5OaeaS97xa9a6RenodGk29D9zlMlwys'
})
export default {
  props: {
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileList: [],
      percent: 0,
      percentShow: false,
      attr: ''
    }
  },
  mounted() {
    this.attr = this.limit ? 'limit' : ''
  },
  methods: {
    // 移除图片
    removeFn(file, fileList) {
      // this.fileList = []
      const url = file.url
      const index = this.fileList.findIndex(item => item.url === url)
      this.fileList.splice(index, 1)
    },
    // 上传图片
    uploadFn(file) {
      console.log(17, file)
      // this.fileList.push({
      //   url: ''
      // })
      this.percentShow = true
      // 图片上传到腾讯云中
      cos.putObject({
        Bucket: 'hr-project-1312551914', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: (Date.now()).toString(), /* 必须 */
        StorageClass: 'STANDARD',
        Body: file.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // progressData  图片加载对象
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        const obj = {}
        console.log(err || data)
        if (err) {
          return this.$message.error('图片上传失败')
        }
        obj['url'] = 'http://' + data.Location
        console.log(78, obj)
        this.fileList.push(obj)
        console.log(this.fileList)
        const time = setTimeout(() => {
          this.percentShow = false
          clearTimeout(time)
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss">
  .disable{
    .el-upload--picture-card{
      display: none;
    }
  }
  .image-upload{
    display: inline-block;
    .el-progress{
      width: 100%;
    }
  }
</style>
